<?php

/**
 * 根据levle 参数和 ck_log_threshold参数写日志
 * @param $level
 * @param $msg
 */
function logger($level='debug', $msg="")
{
     global $ck_config;
     if($ck_config['log_threshold'] == 0)
     {
         return false;
     }
     else if($ck_config['log_threshold'] == 1)
     {
         if(strtolower($level) == 'error')
         {
             write_log('error',$msg);
         }
     }
     else if($ck_config['log_threshold'] == 2)
     {
         if(strtolower($level) == 'error' || strtolower($level) == 'debug')
         {
             write_log(strtolower($level),$msg);
         }
     }
    return true;   
}

/**
 * 写日志
 * @param $level
 * @param $msg
 * @param $path 
 */
function write_log($level='debug' , $msg ='' , $path = '')
{
    if(!file_exists(DIR_ROOT.'/logs'))
    {
       mkdir(DIR_ROOT.'/logs',DIR_WRITE_MODE); 
    }
     if($path == '')
     {
         $filepath = DIR_ROOT.'/logs/log-'.date('Y-m-d').".php";
     }
     else
     {
         $filepath = DIR_ROOT .'/logs/'.$path;
     }
     $message = '' ; 
	 if(! file_exists($filepath))
	 {
		$message = "<"."?php  if ( ! defined('DIR_ROOT')) exit(''); ?".">\n\n";
	 }
	 if( ! $fp = @fopen($filepath, 'ab'))
	 {
         return false;
	 }
	 $message .= $level.' '.date('Y-m-d H:i:s'). ' --> '.$msg."\n";
	 flock($fp, LOCK_EX);	
	 fwrite($fp, $message);
	 flock($fp, LOCK_UN);
	 fclose($fp);
	 @chmod($filepath, 0666); 
	 return true;
}

//TODO
function show_error($msg,$code)
{
    show_error_gen($msg,$msg);
}


function show_404($msg)
{
	header("");
	echo "404 error!";
	exit();
//      show_error_gen($msg,$msg);
}

function show_error_gen($heading, $message, $template = 'error_general', $status_code = 500)
{
	
}

/**
 * 加载一个视图,并通过第二个参数赋值
 * @param string $htmlFile
 * @param array $data
 */
function view($htmlFile , $data=array())
{
    global $ck_config;
    require_once DIR_CLASS.'/CK_Template'.EXT;
    $config['file_name'] = $htmlFile;
    $config['base_dir'] = DIR_ROOT;
    $template = new CK_Template($config);
    $template->assign($data);
    isset($ck_config['skin'])? $skin = $ck_config['skin'] : $skin = "default"  ;
    $template->assign('static',$ck_config['base_url'].'/static/'.$skin);//将会覆盖前面$data['static'],也可以考虑不覆盖
    $template->output();
    return $template;
}

/* TODO
 * 不知道怎么让user通过func来调用到get_user_list();
 */ 
function model($model_name, $func, $data = array())
{
	require_once DIR_CLASS.'/CK_Model'.EXT;
	require_once DIR_MODEL."/$model_name".'_model'.EXT;
	$user = new $model_name();
	$user->get_user_list();
}

/**
 * 返回基础URL
 */
function base_url()
{
    global $ck_config;
    return $ck_config['base_url'];
}
